﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using HanhuaMicroCredit.BLL;
using Library.Bll;

namespace Main.Controllers
{
    public class InterfaceController : Controller
    {
        //
        // GET: /Interface/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Default()
        {
            return Content("interface default page. version: 1.20130314.1500");
        }

        /// <summary>
        /// 获取省份
        /// </summary>
        /// <returns></returns>
        public JsonResult Province()
        {
            return Json(DistrictBLL.GetProvinces(), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取城市
        /// </summary>
        /// <param name="id">省编码</param>
        /// <returns></returns>
        public JsonResult City(int? id)
        {
            return Json(DistrictBLL.GetCities(id), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取区域
        /// </summary>
        /// <param name="id">城市编码</param>
        /// <returns></returns>
        public JsonResult Districts(int? id)
        {
            return Json(DistrictBLL.GetDistricts(id), JsonRequestBehavior.AllowGet);
        }

        public ContentResult IsIdCardExist(string idCard)
        {
            if (!CheckIdCardExist(idCard))
                return Content("0"); //没有相关身份证号
            return Content("1"); 
        }

        public ContentResult IsPhoneExist(string phone)
        {
            if (!CheckPhoneExist(phone))
                return Content("0"); //没有相关手机号
            return Content("1");
        }

        public bool CheckIdCardExist(string idCard)
        {
            string table = "tmp_Loan_InfoList";
            string column = "*";
            string condition = string.Format("isvalid = 1 and idcard='{0}'", idCard.Trim().Replace("'", "''"));
            List<Dictionary<string, object>> ls = CommonBLL.GetList(table, column, "", condition);
            if (ls.Count < 1)
                return false; //没有相关手机号
            return true;
        }

        public bool CheckPhoneExist(string phone)
        {
            string table = "tmp_Loan_InfoList";
            string column = "*";
            string condition = string.Format("isvalid = 1 and phone='{0}'", phone.Trim().Replace("'", "''"));
            List<Dictionary<string, object>> ls = CommonBLL.GetList(table, column, "", condition);
            if (ls.Count < 1)
                return false; //没有相关手机号
            return true;
        }
        public ContentResult smstest()
        {
            OrderNotice on = new OrderNotice();
            return Content(on.smstest());
        }

        public ContentResult smsReg()
        {
            OrderNotice on = new OrderNotice();
            return Content("register status: " + on.Reg().ToString());
        }

        public ContentResult smsUnReg()
        {
            OrderNotice on = new OrderNotice();
            return Content("UnRegister status: " + on.UnReg().ToString());
        }

        public ContentResult smsBalance()
        {
            string balance = string.Empty;
            OrderNotice on = new OrderNotice();
            int status = on.GetBalance(out balance);
            return Content("GetBalance status: " + status.ToString() + "; Balance: " + balance);
        }

        Webservice.SDKService sdkService = new global::Main.Webservice.SDKService();
        /// <summary>
        /// 发短信验证码
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        //public ActionResult SengSmsVCode(FormCollection fc)
        [HttpPost]
        public ContentResult SengSmsVCode(string idCard, string mobile, bool IsAddSession)
        {
            try
            {
                if (!CheckIdCardExist(idCard))
                {
                    return Content("41");
                }
                if (!CheckPhoneExist(mobile))
                {
                    return Content("42");
                }
                //string idCard = fc["txtIdCard"];
                //string mobile = fc["txtPhone"];
                string ip = GetClientIP();

                #region 验证验证码发送是否过于频繁
                //int smsInterval = ConfigurationManager.AppSettings["smsInterval"] != null
                //    ? int.Parse(ConfigurationManager.AppSettings["smsInterval"].ToString()) : 60;
                //List<Dictionary<string, object>> logs = CommonBLL.GetList("Order_NoticeLog", "createdate", "id desc"
                //    , string.Format("(ipAddress is not null) and ipAddress='{0}' and datediff(ss,createdate,getdate())<{1}", ip, smsInterval));

                //if (logs.Count > 0)
                //{
                //    return Content("7"); //7 - 接收信息过于频繁
                //}
                #endregion 

                string pwd = HanhuaMicroCredit.BLL.Utility.Utils.getRdCode(6).ToLower();
                string con = string.Format("尊敬的用户您好，您的验证码是{0}。【瀚华信贷】", pwd);

                //int status = OrderNotice.sendSms(mobile, con);
                int status = sdkService.sendSMS(ConfigurationManager.AppSettings["smsKey"].ToString()
                    , ConfigurationManager.AppSettings["smsK"].ToString(), "",
                        mobile.Trim().ToString().Split(new char[] { ',' }), con.Trim().ToString(),
                        "", "GBK", 3,
                        Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssfff")));

                //插入数据库记录
                Dictionary<string, object> nextDic = new Dictionary<string, object>();
                nextDic.Add("noticeType", 3);
                nextDic.Add("MTelOrEmail", mobile);
                nextDic.Add("noticeContent", con);
                nextDic.Add("ontime", DateTime.Now.ToString());
                nextDic.Add("status", status);
                nextDic.Add("ipAddress", ip);

                int i = CommonBLL.Add("Order_NoticeLog", nextDic);
                if (status == 0)
                {
                    Session["_RegIdCard"] = idCard;
                    Session["_RegMobile"] = mobile;
                    Session["_RegValCode"] = pwd;
                    Dictionary<string, object> val = new Dictionary<string,object>();
                    val["phone"] = mobile;
                    val["vcode"] = pwd;
                    CommonBLL.Add("Loan_Validate", val);
                    return Content("1");
                }
                else
                {
                    InsLogBll.InsertLog("", "发验证码出错", "短信发送状态码", status.ToString());
                    return Content(status.ToString());
                }
            }
            catch (Exception e)
            {
                InsLogBll.InsertLog("", "发验证码异常", "短信发送状态码", e.Message);
                return Content("9");
            }
        }

        private string GetClientIP()
        {
            string result = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = Request.UserHostAddress;
            }
            return result;
        }
    }
}
